package org.quadraspace.support;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Collections;

import org.glassfish.embed.*;

public class OnTheFlyTestServer {
	private static final int TEST_PORT = 9998;
	private static final String appName = "QuadraServer";
	private static GlassFish gfInstance = null;
	private static ScatteredWar war = null;
	public static String resourcesFile = "src/main/resources";
	public static String webXmlLocation = "src/main/webapp/WEB-INF/web.xml";

	public static String getBaseUrl() {
		return "http://localhost:" + TEST_PORT + "/" + appName;
	}

	public static void startUp() {
		try {
			war = new ScatteredWar(appName, new File(resourcesFile), new File(
					webXmlLocation), Collections.singleton(new File(
					"target/classes").toURI().toURL()));
		} catch (MalformedURLException e) {
			// should happen only if the project folder structure is changed
			e.printStackTrace();
		}
		gfInstance = new GlassFish(TEST_PORT);
		try {			
			gfInstance.deploy(war);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static void stop() {
		if (gfInstance != null) {
			gfInstance.stop();
			gfInstance = null;
		}
	}
}
